package com.meaningful.thinking.netty_demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.TimeUnit;

public class NettyClient {

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new LineBasedFrameDecoder(1024))
                                .addLast(new StringEncoder())
                                .addLast(new StringDecoder())
                                .addLast(new SimpleChannelInboundHandler<String>() {

                                    @Override
                                    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                        System.out.println(msg);
                                    }

                                });
                    }

                });

        ChannelFuture connected = bootstrap.connect("127.0.0.1", 8080);

        connected.addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("成功连接了8080");
                EventLoop eventExecutors = connected.channel().eventLoop();
                eventExecutors.scheduleAtFixedRate(
                        () -> {
                            connected.channel().writeAndFlush("hello" + System.currentTimeMillis() + "\n");
                        },
                        0,
                        1,
                        TimeUnit.SECONDS
                );
            } else {
                System.out.println("服务器连接失败");
            }
        });
    }

}
